import { 
  Box, 
  Text, 
  Flex, 
  useColorModeValue, 
  Avatar
} from '@chakra-ui/react';
import { ReactNode } from 'react';

export interface Message {
  id: string;
  content: string;
  sender: 'user' | 'ai';
  timestamp: Date;
}

interface MessageBubbleProps {
  message: Message;
  children?: ReactNode;
}

export const MessageBubble = ({ message, children }: MessageBubbleProps) => {
  const isUser = message.sender === 'user';
  
  const userBgColor = useColorModeValue('blue.100', 'blue.700');
  const aiBgColor = useColorModeValue('gray.100', 'gray.700');
  const userTextColor = useColorModeValue('gray.800', 'white');
  const aiTextColor = useColorModeValue('gray.800', 'white');
  
  // 处理消息中的换行符
  const formattedContent = message.content.split('\n').map((line, index) => (
    <Text key={index}>{line || ' '}</Text>
  ));

  return (
    <Flex 
      justifyContent={isUser ? 'flex-end' : 'flex-start'} 
      mb={4}
      w="100%"
    >
      {!isUser && (
        <Avatar 
          size="sm" 
          name="AI Assistant" 
          src="/ai-avatar.png" 
          mr={2}
        />
      )}
      
      <Box
        maxW="70%"
        bg={isUser ? userBgColor : aiBgColor}
        color={isUser ? userTextColor : aiTextColor}
        p={3}
        borderRadius="lg"
        borderBottomRightRadius={isUser ? 0 : 'lg'}
        borderBottomLeftRadius={isUser ? 'lg' : 0}
      >
        <Box>{formattedContent}</Box>
        {children}
        <Text 
          fontSize="xs" 
          color={isUser ? 'blue.600' : 'gray.500'} 
          textAlign="right" 
          mt={1}
        >
          {new Date(message.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
        </Text>
      </Box>
      
      {isUser && (
        <Avatar 
          size="sm" 
          name="User" 
          src="/user-avatar.png" 
          ml={2}
        />
      )}
    </Flex>
  );
};

export default MessageBubble; 